package com.min.state.machine;

import com.min.state.machine.event.*;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Data
public class StateMachine {

    List<StateTransition> stateTransitionList = Arrays.asList(
            StateTransition.builder()
                    .currentState(State.START)
                    .nextState(State.INPUT)
                    .event(new InputEvent()).build(),
            StateTransition.builder()
                    .currentState(State.INPUT)
                    .nextState(State.TEST)
                    .event(new TestEvent()).build(),
            StateTransition.builder()
                    .currentState(State.TEST)
                    .nextState(State.REPORT)
                    .event(new ReportEvent()).build()
    );

    private State state;

    public StateMachine(State state) {
        setState(state);
    }

    public void event(EventEnum e) throws InvalidEventException {
        Optional<StateTransition> transitionOptional = stateTransitionList.stream()
                .filter(transition -> transition.getEvent().event().equals(e) && transition.getCurrentState().equals(state))
                .findFirst();

        if (!transitionOptional.isPresent()) {
            throw new InvalidEventException("未找到状态转换条件");
        }

        StateTransition transaction = transitionOptional.get();
        if (transaction.getEvent().action()) {
            setState(transaction.getNextState());
        }
    }

}
